package com.ruoyi.common.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author : Hz～
 * @version : 1.0
 * @date : 2024-06-11 10:22
 * @Description :
 **/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");
        this.strictInsertFill(metaObject, "createTime", Date.class, DateUtils.getNowDate());
        this.strictUpdateFill(metaObject, "updateTime", Date.class, DateUtils.getNowDate());
        LoginUser loginUser = BeanUtil.toBean(SecurityUtils.getAuthentication(), LoginUser.class);
        if (ObjUtil.isNotEmpty(loginUser)) {
            this.strictInsertFill(metaObject, "createBy", String.class, String.valueOf(loginUser.getUserId()));
            this.strictUpdateFill(metaObject, "updateBy", String.class, String.valueOf(loginUser.getUserId()));
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        try {
            this.setFieldValByName("updateTime", DateUtils.getNowDate(), metaObject);
            LoginUser loginUser = BeanUtil.toBean(SecurityUtils.getAuthentication(), LoginUser.class);
            if (ObjUtil.isNotEmpty(loginUser)) {
                this.setFieldValByName("updateBy", loginUser.getUserId(), metaObject);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
